/** \file qQWWSettings.cpp
 * \brief QWordWizard Settings dialog implementation
 */

#include "qwwsettings.h"
#include "qwwdic.h"
#include <QTableWidgetItem>
#include <QFileDialog>
#include <QMessageBox>
#include <QList>
#include <QStringList>

static const QString bad_dictionary_str = "__qwordwizard__no_description__";

QWWSettings::QWWSettings(QWidget *parent)
{
    setParent(parent);
    m_ui.setupUi(this);
    setWindowState(Qt::WindowMaximized | Qt::WindowActive);

    connect(m_ui.btnAdd, SIGNAL(clicked()), this, SLOT(AddDictionary()));
    connect(m_ui.btnEdit, SIGNAL(clicked()), this, SLOT(EditDictionary()));
    connect(m_ui.btnRemove, SIGNAL(clicked()), this, SLOT(RemoveDictionary()));
}

QWWSettings::~QWWSettings()
{

}

int QWWSettings::GetInterval() const
{
    if (m_ui.rbtn10->isChecked())
        return 10;
    if (m_ui.rbtn15->isChecked())
        return 15;
    if (m_ui.rbtn30->isChecked())
        return 30;

    return 60;
}

void QWWSettings::SetInterval(int interval)
{
    switch (interval)
    {
        case 10:
            m_ui.rbtn10->setChecked(true);
            break;
        case 15:
            m_ui.rbtn15->setChecked(true);
            break;
        case 30:
            m_ui.rbtn30->setChecked(true);
            break;
        case 60:
        default:
            m_ui.rbtn60->setChecked(true);
            break;
    }
}

void QWWSettings::GetDictionaries(vector<pair<bool, QString> > &dic) const
{
    dic.clear();
    for (int i = 0; i < m_ui.tblDic->rowCount(); i++)
    {
        bool used = m_ui.tblDic->item(i, 0)->checkState() == Qt::Unchecked ? false : true;
        QString filename = m_ui.tblDic->item(i, 2)->text();
        dic.push_back(make_pair(used, filename));
    }
}

void QWWSettings::SetDictionaries(const vector<pair<bool, QString> > &dic)
{
    for(vector<pair<bool, QString> >::const_iterator it = dic.begin(); it != dic.end(); ++it)
    {
        QString description = GetDictionaryDescription(it->second);
        InsertTableLine(it->first, description, it->second);
    }
}

void QWWSettings::InsertTableLine(bool used, QString description, QString path)
{
    int row_position = m_ui.tblDic->rowCount();
    m_ui.tblDic->insertRow(row_position);

    // "Used"
    QTableWidgetItem *item_used = new QTableWidgetItem();
    item_used->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
    if (used)
        item_used->setCheckState(Qt::Checked);
    else
        item_used->setCheckState(Qt::Unchecked);
    item_used->setTextAlignment(Qt::AlignHCenter);
    m_ui.tblDic->setItem(row_position, 0, item_used);

    // "Description"
    QTableWidgetItem *item_description = new QTableWidgetItem();
    item_description->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
    item_description->setText(description);
    m_ui.tblDic->setItem(row_position, 1, item_description);

    // "Path"
    QTableWidgetItem *item_path = new QTableWidgetItem();
    item_path->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
    item_path->setText(path);
    m_ui.tblDic->setItem(row_position, 2, item_path);

    m_ui.tblDic->resizeColumnsToContents();
}

void QWWSettings::AddDictionary()
{
    QString description;
    QString filename = QFileDialog::getOpenFileName(this,
            tr("Add dictionary"),
            "",
            tr("Dictionary files(CSV)(*.csv)"));
//            tr("Dictionary files(XML)(*.xml);;Dictionary files(CSV)(*.csv)"));
    if (filename.isNull())
        return;

    // Check for existing
    QList<QTableWidgetItem *> list = m_ui.tblDic->findItems(filename, Qt::MatchExactly);
    if (!list.empty())
    {
        QMessageBox::warning(this, "QWordWizard", tr("This dictionary already exist in your list"));
        return;
    }

    description = GetDictionaryDescription(filename);
    if (description != bad_dictionary_str)
        InsertTableLine(true, description, filename);
}

QString QWWSettings::GetDictionaryDescription(QString filename)
{
    QString description = bad_dictionary_str;
    QWWDic *p = QWWDic::Instance();
    try
    {
        // Determine file type
        QStringList lst;
        lst = filename.split(".");
        if (lst.at(lst.size() - 1).toLower() == "xml")
            description = p->Preload(filename, e_xml);
        else
            description = p->Preload(filename, e_csv);
    }
    catch (exception &e)
    {
        QMessageBox::critical(this, "QWordWizard", e.what() + QString(":\n") + filename);
    }

    return description;
}

void QWWSettings::RemoveDictionary()
{
    int current_row = m_ui.tblDic->currentRow();
    if (current_row < 0)
        return;

    if (QMessageBox::question(this,
                "QWordWizard",
                tr("Do you really want to remove it from the table?"),
                QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)
        m_ui.tblDic->removeRow(m_ui.tblDic->currentRow());
}

void QWWSettings::EditDictionary()
{
    int current_row = m_ui.tblDic->currentRow();
    if (current_row < 0)
        return;

    QString description;
    QString filename = QFileDialog::getOpenFileName(this,
            tr("Change dictionary"),
            "",
            tr("Dictionary files(CSV)(*.csv)"));
//            tr("Dictionary files(XML)(*.xml);;Dictionary files(CSV)(*.csv)"));
    if (filename.isNull())
        return;

    // Check for existing
    QList<QTableWidgetItem *> list = m_ui.tblDic->findItems(filename, Qt::MatchExactly);
    if (!list.empty())
    {
        QMessageBox::warning(this, "QWordWizard", tr("This dictionary already exist in your list"));
        return;
    }

    description = GetDictionaryDescription(filename);

    m_ui.tblDic->item(current_row, 0)->setCheckState(Qt::Unchecked);
    m_ui.tblDic->item(current_row, 1)->setText(description);
    m_ui.tblDic->item(current_row, 2)->setText(filename);
    m_ui.tblDic->resizeColumnsToContents();
}
